package seismosurfer.servlets;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import oracle.ord.im.OrdDoc;
import oracle.ord.im.OrdHttpResponseHandler;
import seismosurfer.data.DocumentMetaData;
import seismosurfer.database.DocumentDAO;
import seismosurfer.servlets.util.ServletUtil;
import seismosurfer.util.SeismoException;

import com.bbn.openmap.util.Debug;

/**
 * This servlet shows a list of documents related
 * to an earthquake or sends a document to the browser.
 *
 */
public class ShowDocServlet extends BaseServlet {
    
    private static final long serialVersionUID = -8987733081762004528L;
    
    private static String jdbcURL;
    
    private static final String METADATA = "metadata";

    // Initialize global variables
    public void init() throws ServletException {
        jdbcURL = getServletContext().getInitParameter("jdbcURL");
    }

    // Process the HTTP Get request
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        DocumentDAO docDAO = new DocumentDAO(jdbcURL);

        long quakeid;
        String qid = request.getParameter(QUAKEID);

        if (qid != null) {

            try {
                quakeid = Long.parseLong(qid);
            } catch (NumberFormatException e) {
                quakeid = 0;
                ServletUtil.displayUserError(response);
                return;
            }
            System.out.println("showdoc quakeid: " + quakeid);

            List docMeta = docDAO.getDocumentsMetadata(quakeid);
            String url = request.getRequestURL().toString();

            String metadata = getMetaDataHtmlTable(docMeta, url);

            request.setAttribute(QUAKEID, new Long(quakeid));
            request.setAttribute(METADATA, metadata);

            forward("/showdoc.jsp", request, response);
        }

        long docid;
        String dID = request.getParameter("docid");

        if (dID != null) {

            try {
                docid = Integer.parseInt(dID);
            } catch (NumberFormatException e) {
                docid = 0;
                ServletUtil.displayUserError(response);
                return;
            }
            System.out.println("showdoc docid: " + docid);

            sendDocument(docid, request, response, docDAO);
            return;
        }

        ServletUtil.displayUserError(response);
    }    

    private String getMetaDataHtmlTable(List docMeta, String requestURL) {

        String rows = "";
        String paramName = "?docid=";
        String bgcolor = "";

        for (int i = 0; i < docMeta.size(); i++) {
            DocumentMetaData md = (DocumentMetaData) docMeta.get(i);
            Debug.output(md.getInfo());

            bgcolor = getBGColor(i);

            rows += "<tr " + bgcolor + "> " +

            toTD(md.getDescription()) +

            toTD(md.getInfo()) +

            toTD(md.getMimeType()) +

            toTD(md.getContentLength() + " bytes ");

            String url = null;
            String srcType = md.getSourceType();

            if (srcType != null && srcType.equalsIgnoreCase("HTTP")) {
                url = md.getSource() + "\" > ";
            } else {
                url = requestURL + paramName + md.getDocumentID() + "\" > ";
            }

            rows += toTD("<a href=\"" + url + md.getSourceName() + "</a> ")
                    + "</tr> ";

        }

        return rows;
    }

    private void sendDocument(long docid, HttpServletRequest request,
            HttpServletResponse response, DocumentDAO docDAO)
            throws ServletException, IOException {

        try {
            OrdHttpResponseHandler handler = new OrdHttpResponseHandler(
                    request, response);
            OrdDoc doc = docDAO.getDocument(docid);

            if (doc != null) {
                handler.sendDoc(doc);
            } else {
                ServletUtil.displayUserError(response);
            }
        } catch (SQLException e) {
            throw new SeismoException(e);
        }

    }

    // Clean up resources
    public void destroy() {

    }

}
